<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { sendChatMessage, getChatHistory, getChatHistoryById, deleteChatApi } from '../api/chat'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import {PlusIcon, UserCircleIcon, ComputerDesktopIcon} from '@heroicons/vue/24/outline'

const route = useRoute()
const router = useRouter()
const messages = ref([])
const inputText = ref('')
const isLoading = ref(false)

const chatList = ref([])
const activeChatId = ref(null)

// 计算id最小的那条的id
const minId = computed(() => {
  if (!chatList.value.length) return null
  return Math.min(...chatList.value.map(c => c.id))
})

const messagesContainer = ref(null)

const tipMsg = ref('')
const tipType = ref('success') // 'success' | 'error'

const userStore = useUserStore()

const showTip = (msg, type = 'success') => {
  tipMsg.value = msg
  tipType.value = type
  setTimeout(() => {
    tipMsg.value = ''
  }, 1500)
}

onMounted(async () => {
  // 在组件挂载时检查登录状态
  if (!userStore.id) {
    ElMessage.warning('未登录，请先登录')
    router.push('/login')
    return
  }
  // 获取历史对话
  try {
    const history = await getChatHistory(userStore.id)
    if (history.data.code === 0) {
      ElMessage.error(history.data.data || '获取历史对话失败')
      return
    }
    if (history && Array.isArray(history.data.data) && history.data.data.length > 0) {
      chatList.value = history.data.data.slice().sort((a, b) => b.chatId - a.chatId)
      // 只有在没有新问题时才加载第一条历史记录
      if (!route.query.question?.trim()) {
        activeChatId.value = chatList.value[0].chatId
        loadChatMessages(activeChatId.value)
      }
    }
  } catch (e) {
    ElMessage.error(e.response?.data?.data || '获取历史对话失败')
  }

  // 如果有新问题，创建新对话
  if (route.query.question && route.query.question.trim()) {
    const newId = Date.now()
    chatList.value.unshift({
      chatId: newId,
      messageTitle: route.query.question,
      isLocal: true // 本地新建
    })
    activeChatId.value = newId
    messages.value = [] // 清空消息列表
    inputText.value = route.query.question
    await sendMessage(newId)

    // 关键：处理完后清空 query
    router.replace({ path: '/chat', query: {} })
  }


})

const sendMessage = async (customChatId) => {
  const question = inputText.value.trim()
  if (!question) return

  messages.value.push({ role: 'user', content: question })
  inputText.value = ''
  isLoading.value = true

  const aiMsg = { role: 'assistant', content: '', loading: true }
  messages.value.push(aiMsg)

  // 更新本地对话的标题
  const chat = chatList.value.find(c => c.chatId === activeChatId.value)
  if (chat && chat.isLocal) {
    chat.messageTitle = question
  }

  try {
    const chatId = activeChatId.value || Date.now()
    const stream = await sendChatMessage(chatId, question, userStore.id)
    const reader = stream.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''
    let received = false

    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })

      let lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const dataContent = line.slice(5).trim()
          if (dataContent) {
            aiMsg.content += dataContent
            // 关键：强制触发响应式
            messages.value = [...messages.value]
            if (!received) {
              aiMsg.loading = false
              isLoading.value = false
              received = true
            }
          }
        }
      }
    }
    
    aiMsg.loading = false
    isLoading.value = false

    // AI回复完成后，重新获取对话历史
    try {
      const history = await getChatHistory(userStore.id)
      if (history.data.code === 0) {
        ElMessage.error(history.data.data || '获取历史对话失败')
        return
      }
      if (history && Array.isArray(history.data.data) && history.data.data.length > 0) {
        chatList.value = history.data.data.slice().sort((a, b) => b.chatId - a.chatId)
      }
    } catch (e) {
      ElMessage.error(e.response?.data?.data || '获取历史对话失败')
    }

  } catch (error) {
    console.error('Error processing stream:', error)
    aiMsg.content = '抱歉，发生了错误，请稍后重试。'
    aiMsg.loading = false
    isLoading.value = false
    ElMessage.error(error.response?.data?.data || '发送消息失败')
  }
}

const autoResize = (event) => {
  const textarea = event.target
  textarea.style.height = 'auto'
  const newHeight = Math.min(textarea.scrollHeight, 150)
  textarea.style.height = newHeight + 'px'
  if (textarea.scrollHeight > 150) {
    textarea.scrollTop = textarea.scrollHeight
  }
}

const startNewChat = () => {
  const timestamp = Date.now()
  const idStr = String(timestamp).slice(-8) // 取时间戳后8位
  chatList.value.push({ chatId: timestamp, messageTitle: idStr, isLocal: true })
  chatList.value.sort((a, b) => b.chatId - a.chatId)
  messages.value = []
  activeChatId.value = timestamp
}

const loadChatMessages = async (chatId) => {
  activeChatId.value = chatId
  const chat = chatList.value.find(c => c.chatId === chatId)
  if (chat && chat.isLocal) {
    messages.value = []
    return
  }
  try {
    const res = await getChatHistoryById(chatId, userStore.id)
    if (res.code === 0) {
      ElMessage.error(res.data.data || '加载聊天记录失败')
      messages.value = []
      return
    }
    
    // 确保数据格式正确
    if (Array.isArray(res.data)) {
      messages.value = res.data.map(msg => ({
        role: msg.role || 'user',
        content: msg.content || ''
      }))
    } else {
      messages.value = []
    }
  } catch (e) {
    ElMessage.error(e.response?.data?.data || '加载聊天记录失败')
    messages.value = []
  }
}

// 每次 messages 变化后滚动到底部
watch(
  () => messages.value.length,
  async () => {
    await nextTick()
    const el = messagesContainer.value
    if (el && el.scrollHeight > el.clientHeight + 2) {
      el.scrollTop = el.scrollHeight
    }
  }
)

const handleSubmit = () => {
  if (inputText.value.trim()) {
    router.push({
      path: '/chat',
      query: { question: inputText.value.trim() }
    }).then(() => {
      // 跳转后立即清空 query，防止刷新时重复创建
      router.replace({ path: '/chat', query: {} })
    })
  }
}

const deleteChat = async (chatId) => {
  try {
    const response = await deleteChatApi(chatId, userStore.id)
    if (response.data.code === 0) {
      ElMessage.error(response.data.data || '删除失败')
      return
    }
    // 删除成功后再更新前端
    const idx = chatList.value.findIndex(c => c.chatId === chatId)
    if (idx !== -1) {
      chatList.value.splice(idx, 1)
      // 如果当前删除的是激活的，切换到下一个
      if (activeChatId.value === chatId) {
        if (chatList.value.length) {
          activeChatId.value = chatList.value[0].chatId
          loadChatMessages(activeChatId.value)
        } else {
          activeChatId.value = null
          messages.value = []
        }
      }
    }
    showTip('删除成功', 'success')
  } catch (e) {
    ElMessage.error(e.response?.data?.data || '删除失败')
  }
}
</script>

<template>
  <div v-if="tipMsg" :class="['global-tip', tipType]">{{ tipMsg }}</div>
  <div class="chat-root">
    <!-- 左侧聊天列表 -->
    <aside class="chat-list-card">
      <div class="chat-list-header">
        <span style="font-size: 20px;font-weight: 400;">聊天记录</span>
        <button class="new-chat-btn" @click="startNewChat">
          <PlusIcon class="icon" />
           新对话</button>
      </div>
      <div class="chat-list-scroll">
        <template v-if="chatList.length === 0">
          <div class="no-data-text">暂无聊天记录</div>
        </template>
        <template v-else>
          <div
            v-for="chat in chatList"
            :key="chat.chatId"
            :class="['chat-list-item', { active: chat.chatId === activeChatId }]"
            @click="loadChatMessages(chat.chatId)"
          >
            <span class="chat-list-left">
              <span class="chat-list-icon">💬</span>
              <span class="chat-list-title">
                {{ chat.messageTitle.length > 7 ? chat.messageTitle.slice(0, 7) + '...' : chat.messageTitle }}
              </span>
            </span>
            <button class="chat-list-delete" @click.stop="deleteChat(chat.chatId)">
              删除
            </button>
          </div>
        </template>
      </div>
    </aside>

    <!-- 右侧主聊天区 -->
    <section class="chat-main-card">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(msg, idx) in messages"
          :key="`${idx}-${msg.content}`"
          :class="['chat-bubble-row', msg.role]"
        >
          <template v-if="msg.role === 'assistant'">
            <span class="bubble-avatar">
              <!-- AI默认icon -->
              <ComputerDesktopIcon style="width:32px;height:32px;color:#b3d1ff;" />
            </span>
            <span class="chat-bubble assistant">
              <span class="bubble-content">
                <template v-if="msg.loading">
                  <span class="loading-spinner"></span>
                </template>
                <template v-else>
                  {{ msg.content }}
                </template>
              </span>
            </span>
          </template>
          <template v-else>
            <span class="chat-bubble user">
              <span class="bubble-content">{{ msg.content }}</span>
            </span>
            <span class="bubble-avatar">
              <!-- 用户默认icon -->
              <UserCircleIcon style="width:32px;height:32px;color:#b3d1ff;" />
            </span>
          </template>
        </div>
      </div>
      <div class="chat-input-bar">
        <textarea
          v-model="inputText"
          placeholder="给DeepSeek发送消息..."
          class="input-box"
          rows="1"
          @input="autoResize"
          @keydown.enter.prevent="sendMessage"
        ></textarea>
        <button
          class="send-btn"
          :disabled="!inputText.trim() || isLoading"
          @click="sendMessage"
        >
          <svg width="24" height="24" viewBox="0 0 24 24"><path d="M2 21l21-9-21-9v7l15 2-15 2z" fill="#fff"/></svg>
        </button>
      </div>
    </section>
  </div>
</template>

<style scoped>
.chat-root {
  display: flex;
  gap: 24px;
  background: #f0f2f5;
  padding: 24px 24px 0 24px;
  justify-content: center;
  align-items: center;
}

.chat-list-card {
  width: 300px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.06);
  padding: 16px 0 16px 0;
  display: flex;
  flex-direction: column;
  height: min(700px, calc(100vh - 60px - 48px));
  max-height: min(700px, calc(100vh - 60px - 48px - 28px));
}
.chat-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px 20px 20px;
  font-weight: 600;
  font-size: 16px;
}
.new-chat-btn {
  display: flex;
  align-items: center;
  background: #007cf0;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 4px 12px;
  font-size: 18px;
  font-weight: 200;
  cursor: pointer;
  transition: background 0.2s;
}

.new-chat-btn .icon {
  width: 20px;
  height: 20px;
  margin-right: 4px;
}
.new-chat-btn:hover {
  background: #005fa3;
}
.chat-list-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}
.chat-list-scroll::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}
.chat-list-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  margin-bottom: 4px;
  transition: background 0.2s;
  justify-content: space-between;
}
.chat-list-item.active, .chat-list-item:hover {
  background: #e6f0ff;
}
.chat-list-icon {
  font-size: 16px;
}
.chat-list-title {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  vertical-align: middle;
}

.chat-main-card {
  flex: 1;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: min(700px, calc(100vh - 60px - 48px));
  max-height: min(700px, calc(100vh - 60px - 48px));
  padding: 0;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px 24px 0 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.chat-messages::-webkit-scrollbar {
  display: none;
}
.chat-bubble-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
}
.chat-bubble-row.assistant {
  justify-content: flex-start;
  align-items: flex-start;
}
.chat-bubble-row.user {
  justify-content: flex-end;
}
.chat-bubble {
  display: flex;
  align-items: center;
  max-width: 60%;
  font-size: 15px;
  box-shadow: 0 1px 2px 0 rgba(0,0,0,0.03);
  padding: 10px 16px;
  border-radius: 12px;
  background: #f8fafd;
}
.chat-bubble.user {
  background: #e6f0ff;
  color: #222;
  border-radius: 12px 12px 0 12px;
  margin-right: 12px;
}
.chat-bubble.assistant {
  background: #f8fafd;
  color: #222;
  border-radius: 12px 12px 12px 0;
  margin-left: 12px;
}
.bubble-avatar {
  display: flex;
  align-items: center;
}
.bubble-content {
  display: block;
  word-break: break-word;
}
.chat-input-bar {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  padding: 16px 24px 16px 24px;
  border-top: 1px solid #f0f2f5;
  background: #fff;
  border-radius: 0 0 16px 16px;
  justify-content: center;
}
.input-box {
  font-size: 15px;
  border: 1.5px solid #e0e0e0;
  border-radius: 8px;
  resize: none;
  overflow-y: scroll;
  min-height: 40px;
  max-height: 120px;
  line-height: 1.5;
  background: #f8fafd;
  scrollbar-width: none;
  -ms-overflow-style: none;
  width: 500px;
}
.input-box::-webkit-scrollbar {
  display: none;
}
.input-box:focus {
  outline: none;
  border-color: #007cf0;
}
.send-btn {
  background: #007cf0;
  border: none;
  border-radius: 8px;
  width: 44px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s;
  padding: 0;
}
.send-btn:disabled {
  background: #b3d1ff;
  cursor: not-allowed;
}
.send-btn:not(:disabled):hover {
  background: #005fa3;
}
.loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid #b3d1ff;
  border-top: 3px solid #007cf0;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  vertical-align: middle;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}
.chat-list-delete {
  margin-left: 8px;
  background: transparent;
  border: none;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 13px;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background 0.2s;
}
.chat-list-delete:hover {
  background: #ffeaea;
}
.chat-list-left {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}
.global-tip {
  position: fixed;
  top: 40px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(240, 255, 240, 0.85); /* 浅色半透明 */
  padding: 10px 32px;
  border-radius: 8px;
  font-size: 16px;
  z-index: 9999;
  opacity: 0.98;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  font-weight: 600;
  min-width: 120px;
  text-align: center;
}
.global-tip.success {
  color: #1bc47d; /* 绿色 */
}
.global-tip.error {
  color: #ff4d4f; /* 红色 */
  background: rgba(255, 240, 240, 0.85); /* 浅红半透明 */
}
@media (max-width: 900px) {
  .chat-list-card {
    display: none;
  }
  .chat-main-card {
    width: 100%;
    min-width: 0;
    max-width: 100vw;
    border-radius: 16px;
  }
}
.no-data-text {
  width: 100%;
  text-align: center;
  color: #bfbfbf;
  font-size: 18px;
  margin-top: 80px;
}
</style> 